#pragma once
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <cstring>
#include <unistd.h>
#include <memory>
#include <string>

#include "Log.hpp"
#include "InetAddr.hpp"
#include "Comm.hpp"
namespace socket_ns
{
    class Socket;
    using SockSPtr = std::shared_ptr<Socket>;

    static const int gbacklog = 8;

    class Socket
    {
    public:
        virtual void CreateSocket() = 0;
        virtual void CreateBind(uint16_t port) = 0;
        virtual void CreateListen() = 0;
        virtual bool Connecter(std::string ip, u_int16_t port) = 0;
        virtual int Accepter(InetAddr *cliaddr,int* code) = 0;
        virtual int Sockfd() = 0;
        virtual void Close() = 0;

        virtual ssize_t Recv(std::string *out) = 0;
        virtual ssize_t Send(const std::string &in) = 0;
        virtual void ReuseAddr() = 0;

    public:
        void BuildListenSocket(uint16_t port)
        {
            CreateSocket();
            ReuseAddr();
            CreateBind(port);
            CreateListen();
        }

        bool BuildClientSocket(std::string ip, u_int16_t port)
        {
            CreateSocket();
            return Connecter(ip, port);
        }
    };

    class TcpSocket : public Socket
    {
    public:
        TcpSocket()
        {
        }

        TcpSocket(int sockfd)
            : _sockfd(sockfd)
        {
        }

        ~TcpSocket()
        {
        }

        void CreateSocket() override
        {
            _sockfd = socket(AF_INET, SOCK_STREAM, 0);
            if (_sockfd < 0)
            {
                LOG(FATAL, "socket create error!\n");
                exit(SOCKET_ERROR);
            }
            SetNoBlock(_sockfd);
            LOG(INFO, "socket create success, sockfd: %d\n", _sockfd);
        }

        void CreateBind(uint16_t port) override
        {
            struct sockaddr_in local;
            memset(&local, 0, sizeof(local));
            local.sin_family = AF_INET;
            local.sin_port = htons(port);
            local.sin_addr.s_addr = INADDR_ANY;
            int n = ::bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n < 0)
            {
                LOG(FATAL, "bind error\n");
                exit(BIND_ERROR);
            }
            LOG(INFO, "Bind success\n");
        }

        void CreateListen() override
        {
            int n = ::listen(_sockfd, gbacklog);
            if (n < 0)
            {
                LOG(FATAL, "listen error\n");
                exit(LISTEN_ERROR);
            }
            LOG(INFO, "listen success\n");
        }

        int Accepter(InetAddr *cliaddr,int* code) override
        {
            struct sockaddr_in client;
            socklen_t len = sizeof(client);
            int sockfd = accept(_sockfd, (struct sockaddr *)&client, &len);
             *code=errno;
            if (sockfd < 0)
            {
                return -1;
            }
            SetNoBlock(sockfd);
            *cliaddr = InetAddr(client);
            LOG(INFO, "get a new link, client info : %s, sockfd is : %d\n", cliaddr->AddrStr().c_str(), sockfd);
            return sockfd; // C++14
        }

        bool Connecter(std::string ip, u_int16_t port) override
        {
            struct sockaddr_in server;
            memset(&server, 0, sizeof(server));
            server.sin_family = AF_INET;
            server.sin_port = htons(port);
            server.sin_addr.s_addr = inet_addr(ip.c_str());

            int n = connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
            if (n < 0)
            {
                return false;
            }
            std::cout << "link success!" << std::endl;
            return true;
        }

        void ReuseAddr()
        {
            int reuse = 1; // 启用套接字重用
            setsockopt(_sockfd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
        }
        int Sockfd()
        {
            return _sockfd;
        }

        void Close()
        {
            if (_sockfd > 0)
            {
                ::close(_sockfd);
            }
        }

        ssize_t Recv(std::string *out) override
        {
            char inbuffer[4096];
            ssize_t n = ::recv(_sockfd, inbuffer, sizeof(inbuffer) - 1, 0);
            if (n > 0)
            {
                inbuffer[n] = 0;
                *out += inbuffer;
            }
            return n;
        }

        ssize_t Send(const std::string &in) override
        {
            return ::send(_sockfd, in.c_str(), in.size(), 0);
        }

    private:
        int _sockfd;
    };
}